import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/token'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import(/* webpackChunkName: "Home" */'@/views/Home'),
    redirect: '/layout/home' // 重定向
  },
  {
    path: '/login',
    component: () => import(/* webpackChunkName: "Login" */'@/views/Login'),
    // 独享守卫
    beforeEnter (to, from, next) {
      if (getToken()?.length > 0) {
        // next(false) // 禁止跳转留在原地 原理：跳转到login页面在跳转过来性能较差
        next('/layout/home') // 直接跳转到首页
      } else {
        next() // 跳转
      }
    }
  },
  {
    path: '/layout',
    component: () => import(/* webpackChunkName: "Layout" */'@/views/Layout'),
    children: [
      {
        path: 'home',
        component: () => import(/* webpackChunkName: "Home" */'@/views/Home'),
        meta: {
          screenT: 0 // 滚动条的距离
        }
      },
      {
        path: 'user',
        component: () => import(/* webpackChunkName: "User" */'@/views/User')
      }
    ]
  },
  {
    path: '/search',
    component: () => import(/* webpackChunkName: "Search" */'@/views/Search')
  },
  {
    path: '/Searchresult/:keywords',
    component: () => import(/* webpackChunkName: "SearchResult" */'@/views/Search/SearchResult')
  },
  {
    path: '/Articledetail',
    component: () => import(/* webpackChunkName: "ArticleDetail" */'@/views/ArticleDetail')
  },
  // 个人信息界面
  {
    path: '/useredit',
    component: () => import(/* webpackChunkName: "Chat" */'@/views/User/UserEdit')
  },
  // 小思同学
  {
    path: '/chat',
    component: () => import(/* webpackChunkName: "Chat" */'@/views/Chat')
  }
]

const router = new VueRouter({
  routes
})

// 全局路由守卫 本地有token时禁止跳转到登录页
// router.beforeEach((to, from, next) => {
//   console.log('**********************')
//   if (getToken()?.length > 0 && to.path === '/login') {
//     next(false) // 禁止跳转留在原地
//     next('/layout/home') // 直接跳转到首页
//   } else {
//     next() // 跳转
//   }
// })

export default router
